package com.errol.batchprocessor.payroll.advisorimpl.online;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.renjia.dao.BusDemandEmployeeMapper;
import com.renjia.dao.CoreUserBankMapper;
import com.renjia.entity.BusDemandEmployee;
import com.renjia.enums.*;
import com.renjia.service.generic.log.LogService;
import com.renjia.service.module.employeeaddition.advisorimpl.payroll.payload.PayrollEmployeeBatchPayload;
import com.renjia.service.module.employeeaddition.advisorimpl.payroll.payload.PayrollEmployeePiecePayload;
import com.renjia.service.module.employeeaddition.advisorimpl.payroll.payload.PayrollEmployeeSinglePayload;
import com.renjia.service.module.payroll.advisor.verify.PayrollVerifyBatchStartAdvisor;
import com.renjia.service.module.payroll.advisor.verify.PayrollVerifySingleValidateAdvisor;
import com.renjia.service.module.payroll.advisor.verify.PayrollVerifySingleValidateEmployeeAdvisor;
import com.renjia.service.module.payroll.advisorimpl.PayrollAdvisorTypeEnum;
import com.renjia.service.module.payroll.advisorimpl.payload.PayLimitPayload;
import com.renjia.util.EpayCallingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 发放限制项的扩展实现
 *
 * @author zhang xiao bin
 * @version v1.0
 * @date 2021/03/06
 * @since v5.0.6
 **/
@Service
public class PayLimitAdvisorImpl
        implements PayrollVerifyBatchStartAdvisor, PayrollVerifySingleValidateAdvisor, PayrollVerifySingleValidateEmployeeAdvisor {

    private final BusDemandEmployeeMapper busDemandEmployeeMapper;
    private final CoreUserBankMapper coreUserBankMapper;
    private final com.renjia.util.EpayCallingService epayCallingService;
    private final LogService logService;

    public PayLimitAdvisorImpl(BusDemandEmployeeMapper busDemandEmployeeMapper,
                               CoreUserBankMapper coreUserBankMapper,
                               EpayCallingService epayCallingService,
                               LogService logService) {
        this.busDemandEmployeeMapper = busDemandEmployeeMapper;
        this.coreUserBankMapper = coreUserBankMapper;
        this.epayCallingService = epayCallingService;
        this.logService = logService;
    }

    @Override
    public boolean shallProcess(@NonNull PayrollEmployeeBatchPayload advisorPayload) {
        return PayrollAdvisorTypeEnum.OFFLINE != advisorPayload.getPayrollAdvisorTypeEnum();
    }

    @Override
    public int priority() {
        return 101;
    }

    @Override
    public boolean doPrepareOnBatchStartAtVerifyStage(@NonNull PayrollEmployeeBatchPayload batchPayload) {
        batchPayload.setPayLimitPayload(new PayLimitPayload(batchPayload.getCoreCustomerChannelMerchant()));
        return true;
    }

    @Override
    public boolean doValidateBeforeFindEmployeeAtVerifyStage(@NonNull PayrollEmployeeSinglePayload singlePayload, @NonNull PayrollEmployeePiecePayload piecePayload, @NonNull PayrollEmployeeBatchPayload batchPayload) {
        if (!piecePayload.getMyBankCardValidator().isValid(singlePayload.getBankCard(), null)) {
            singlePayload.getErrMsgList().add("收款账号格式不正确");
            return false;
        }
        return true;
    }

    @Override
    public boolean doValidateAfterDealWithEmployeeAtVerifyStage(@NonNull PayrollEmployeeSinglePayload singlePayload, @NonNull PayrollEmployeePiecePayload piecePayload, @NonNull PayrollEmployeeBatchPayload batchPayload) {
        if (!UserStatusEnum.NORMAL.getCode().equals(singlePayload.getCoreEmployee().getUserStatus()) ||
                (singlePayload.getCoreEmployeeCustomer() != null && !UserStatusEnum.NORMAL.getCode().equals(singlePayload.getCoreEmployeeCustomer().getUserStatus()))) {
            singlePayload.getErrMsgList().add("该人员已停用或异常");
            return false;
        }
        if (batchPayload.getPayLimitPayload().isPayLimit()) {
            // 只发已存在 coreEmployeeCustomer
            if (singlePayload.getCoreEmployeeCustomer() == null) {
                singlePayload.getErrMsgList().add("不在人员列表中");
                return false;
            }
            if (batchPayload.getPayLimitPayload().getPayAuthenticationFlag() && Boolean.FALSE.equals(batchPayload.getPayLimitPayload().getPayNoAuthenticationFlag())) {
                // 只发已认证
                if (!AuthenticationStatusEnum.AUTHORIZED.getCode().equals(singlePayload.getCoreEmployeeCustomer().getAuthenticationStatus())) {
                    singlePayload.getErrMsgList().add("人员未认证");
                    return false;
                }
            }
            //只发已签约和已补签的
            if (batchPayload.getPayLimitPayload().getPaySigningFlag() && Boolean.FALSE.equals(batchPayload.getPayLimitPayload().getPayNoSigningFlag())) {
                if (!EmployeeSigningStatusEnum.isSigned(singlePayload.getCoreEmployeeCustomer().getSigningStatus())
                        && !EmployeeSigningAgainStatusEnum.isSignedAgain(singlePayload.getCoreEmployeeCustomer().getSigningAgainStatus())) {
                    singlePayload.getErrMsgList().add("人员未签约");
                    return false;
                }
            }
            //只发已接单的人员
            if (PayLimitEnum.ONLY_EXIST.getCode().equals(batchPayload.getPayLimitPayload().getOrderReceivingLimit())) {
                Wrapper<BusDemandEmployee> wrapper = Condition.wrapper();
                wrapper.eq("demand_id", singlePayload.getSingleEntity().getDemandId());
                wrapper.eq("employee_id", singlePayload.getCoreEmployee().getId());
                wrapper.eq("document_number", singlePayload.getSingleEntity().getDocumentNumber());
                wrapper.eq("record_status", DemandEmployeeStatusEnum.ACCEPTED.getCode());
                int count = busDemandEmployeeMapper.selectCount(wrapper);
                if (count == 0) {
                    singlePayload.getErrMsgList().add("人员未接单");
                    return false;
                }
            }
            if (singlePayload.getCoreUserBank() != null) {
                if (!singlePayload.getCoreUserBank().getUserName().equals(singlePayload.getSingleEntity().getEmployeeName())) {
                    logService.remind("发放导入发现银行卡冗余姓名错误，coreUserBank.id=" + singlePayload.getCoreUserBank().getId());
                }
                if (StringUtils.isNotBlank(singlePayload.getCoreUserBank().getBankKey())) {
                    if (StringUtils.isEmpty(singlePayload.getSingleEntity().getRemark2())) {
                        singlePayload.getSingleEntity().setRemark2(singlePayload.getCoreUserBank().getBankKey());
                    }
                    if (StringUtils.isEmpty(singlePayload.getSingleEntity().getRemark3())) {
                        String openBank = singlePayload.getCoreUserBank().getOpenBank();
                        if (StringUtils.isNotBlank(openBank)) {
                            singlePayload.getSingleEntity().setRemark3(openBank.substring(0, openBank.indexOf("银行") + 2));
                        }
                    }
                } else {
                    //查询银行卡联行号
                    Map<String, String> resultMap = epayCallingService.queryBankInfo(singlePayload.getBankCard());
                    if (StringUtils.isNotBlank(resultMap.get("branchNo"))) {
                        singlePayload.getCoreUserBank().setBankKey(resultMap.get("branchNo"));
                        if (StringUtils.isEmpty(singlePayload.getSingleEntity().getRemark2())) {
                            singlePayload.getSingleEntity().setRemark2(resultMap.get("branchNo"));
                        }
                        coreUserBankMapper.updateById(singlePayload.getCoreUserBank());
                    }
                }
            }
        }
        return true;
    }

}
